<template>
  <el-dialog title="执行诊断" :close-on-click-modal="false" :visible.sync="visible" ref="myDialog"
    class="JNPF-dialog JNPF-dialog_center" lock-scroll width="1024px" :modal-append-to-body="false" append-to-body>
    <el-row>
      <el-col :span="24" class="grid-content">
        <div class="hidden-area" style="margin-bottom: 8px;">
          <div class="input-group">
            <label class="input-label no-wrap-cell">故障描述:{{ faultinfo.fault_desc }}</label>
          </div>
        </div>
        <div class="input-group" style="margin-top: 8px;"  v-show="param_url_show">
            <label class="input-label no-wrap-cell">诊断URL:</label>
            <el-input
              type="input"
              v-model="param_url"
              placeholder="输入诊断url"
            ></el-input>
          </div>
          <div class="hidden-area" v-show="param_traffixlog_show" style="margin-top: 8px;">
            <div class="input-group">
              <label class="input-label no-wrap-cell">时间范围:</label>
              <el-date-picker
              v-model="param_dateRange"
              type="datetimerange"
              :picker-options="timePickerOptions"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              ></el-date-picker>
            </div>
            <div class="input-group">
                <label class="input-label no-wrap-cell">分析类型:</label>
                <el-select v-model="param_fxtype" multiple style="width: 500px;">
                  <el-option
                    v-for="item in typeoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </div><div class="input-group">
                <label class="input-label no-wrap-cell">协&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;议:</label>
                <el-radio-group v-model="param_protocol">
                  <el-radio label="http">HTTP</el-radio>
                  <el-radio label="tcp">TCP</el-radio>
                  <el-radio label="udp">UDP</el-radio>
                </el-radio-group>
              </div>
              <div class="input-group" >
                <label class="input-label no-wrap-cell">源地址&nbsp;&nbsp;&nbsp;&nbsp;:</label>
                <el-input style="width: 500px;"
                  type="input"
                  v-model="param_sourceip_port"
                  placeholder="输入源ip和端口:xx.xx.xx.xx:20"
                ></el-input>
              </div>
              <div class="input-group" >
                <label class="input-label no-wrap-cell">目标地址:</label>
                <el-input style="width: 500px;"
                  type="input"
                  v-model="param_targetip_port"
                  placeholder="输入目的ip和端口:xx.xx.xx.xx:20"
                ></el-input>
              </div>
          </div>
          <div class="hidden-area" v-show="param_domain_show" style="margin-top: 8px;">
             <div class="input-group">
                <label class="input-label no-wrap-cell">协&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;议:</label>
                <el-radio-group v-model="param_protocol">
                  <el-radio label="http">HTTP</el-radio>
                  <el-radio label="tcp">TCP</el-radio>
                  <el-radio label="udp">UDP</el-radio>
                </el-radio-group>
              </div>
              <div class="input-group">
                <label class="input-label no-wrap-cell">域&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</label>
                <el-input
                  type="input" style="width: 500px;"
                  v-model="param_domain"
                  placeholder="输入诊断域名"
                ></el-input>
              </div>
              <div class="input-group">
                <label class="input-label no-wrap-cell">运营商&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:</label>
                <el-select v-model="param_operator" placeholder="请选择运营商" style="width: 500px;" clearable>
                <el-option
                    v-for="operator in operators"
                    :key="operator.value"
                    :label="operator.label"
                    :value="operator.value"
                  ></el-option>
                </el-select>
              </div>
              <div class="input-group">
                <label class="input-label no-wrap-cell">省&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;份:</label>
                <el-select v-model="param_province" placeholder="请选择省份" style="width: 500px;" clearable>
                  <el-option
                    v-for="province in provinces"
                    :key="province.value"
                    :label="province.label"
                    :value="province.value"
                  ></el-option>
                </el-select>
              </div>
              <div class="input-group" >
                <label class="input-label no-wrap-cell">源IP和端口&nbsp;&nbsp;&nbsp;:</label>
                <el-input style="width: 500px;"
                  type="input"
                  v-model="param_sourceip_port"
                  placeholder="输入源ip和端口:xx.xx.xx.xx:55353"
                ></el-input>
              </div>
              <div class="input-group">
              <label class="input-label no-wrap-cell">DNS&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:</label>
              <el-input
                type="input" style="width: 500px;"
                v-model="param_dns"
                placeholder="输入dns"
              ></el-input>
            </div>
              <div class="input-group" >
                <label class="input-label no-wrap-cell">目标IP和端口:</label>
                <el-input style="width: 500px;"
                  type="input"
                  v-model="param_targetip_port"
                  placeholder="输入目的ip和端口:xx.xx.xx.xx:80"
                ></el-input>
              </div>
          </div>
          <div class="hidden-area"  style="margin-top: 8px;">
             <div class="input-group">
              <el-steps :active="currentStep" align-center>
                <el-step
                  v-for="(step, index) in steps"
                  :key="index"
                  :title="step.title"
                  :description="step.description"
                  :status="step.status"
                ></el-step>
              </el-steps>
            </div>
          </div>
        <el-table :data="step_list" style="width: 100%; max-height: 350px; overflow: auto;" ref="table"
        @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="操作步骤" prop="step" width="80"></el-table-column>
          <el-table-column label="操作名称" prop="processor_name" width="150">
            <template slot-scope="scope">
              <div class="no-wrap-cell">{{ scope.row.processor_name }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作类型" prop="processor_type" width="100"></el-table-column>
          <el-table-column label="常用操作" prop="isoften" width="80"></el-table-column>
          <el-table-column label="进度" prop="progress" width="200">
            <template slot-scope="scope">
              <!-- <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)"></el-progress>
              <span class="progress-text">{{ formatProgress(scope.row.progress) }}%</span> -->
              <div class="progress-container">
                <el-progress :percentage="formatProgress(scope.row.progress)" class="progress-bar"></el-progress>
                <div v-if="scope.row.diagnosis_result == '通过'" class="status-icon success-icon">
                  <i class="el-icon-check"></i>
                </div>
                <div v-else-if="scope.row.diagnosis_result == '不通过'" class="status-icon exception-icon">
                  <i class="el-icon-close"></i>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="诊断结果" prop="diagnosis_result" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="truncate-lines">
                {{ scope.row.diagnosis_result }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="处置建议" prop="disposal_suggestions_tip" show-overflow-tooltip></el-table-column>
        </el-table>
        
        <el-button style="margin-top: 8px;" type="primary" round @click="executeDiag()">确认执行</el-button>
        <el-button style="margin-top: 8px;" type="warning" round  @click="stopExecution">停止执行</el-button>
        <!-- Hidden Area -->
        
        <div class="hidden-area" v-show="exeFinished" style="margin-top: 8px;">
          <div class="input-group">
            <label class="input-label no-wrap-cell">分析结果:</label>
            <el-input
              type="textarea"
              v-model="diagnosis_result"
              :rows="4"
              placeholder="输入故障原因"
            ></el-input>
          </div>
          <div class="input-group">
            <label class="input-label no-wrap-cell">处置建议:</label>
            <el-input
              type="textarea"
              v-model="disposal_suggestions"
              :rows="4"
              placeholder="输入处置建议"
            ></el-input>
            <!-- <el-button style="margin-top: 8px;" type="primary" round  @click="sendOrder">派发处置工单</el-button> -->
          </div>
          <!-- <div class="input-group">
            <label class="input-label no-wrap-cell">处置结果:</label>
            <el-input
              type="textarea"
              v-model="disposal_result"
              :rows="4"
              placeholder="输入处置结果"
            ></el-input>
          </div> -->
          <el-button style="margin-top: 8px;" type="primary" round  @click="sendOrder">派发处置工单</el-button>
        </div>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { deepClone } from '@/utils'
export default {
  data() {
    const now = new Date();
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    return {
      visible: false,
      btnLoading: false,
      formData: {},
      faultinfo:{},
      init_step_list:[],
      step_list:[],
      task_insert_params:{},
      exeCount:0,
      exeFinishedCount:0,
      exeFinished:false,

      timePickerOptions: {
        format: 'yyyy-MM-dd HH:mm:ss' // 设置时间格式，包括秒
      },
      typeoptions:[
      { label: '异常连接检测', value: '异常连接检测' },
      { label: '拥塞检测', value: '拥塞检测' },
      { label: '恶意活动检测', value: '恶意活动检测' },
      { label: '流量分布分析', value: '流量分布分析' },
      { label: '异常协议行为检测', value: '异常协议行为检测' },
      { label: '数据传输量分析', value: '数据传输量分析' },
      { label: '连接时长分析', value: '连接时长分析' },
      { label: '服务可用性分析', value: '服务可用性分析' },
      { label: '数据泄露检测', value: '数据泄露检测' },
      { label: '连接速率分析', value: '连接速率分析' },
      { label: '网络瓶颈检测', value: '网络瓶颈检测' },
      { label: '链路负载均衡分析', value: '链路负载均衡分析' }
      ],
      fx_results:{
        "异常连接检测":{
          "result":"检测到源IP为:param_sourceip_port,目的IP为:param_targetip_port 的连接持续时间异常，数据传输量异常，可能表明存在恶意活动",
          "sugg":"对检测到的异常连接进行分析，如果确认存在恶意活动，可以采取阻止IP地址、端口或协议，加强安全策略，或者通知安全团队进行进一步调查"
        },
        "拥塞检测":{
          "result":"识别源IP为:param_sourceip_port,目的IP为，目的IP为:param_targetip_port 的连接拥塞程度为高，延迟增加，丢包率上升，建议优化网络带宽或增加链路",
          "sugg":"优化网络带宽或增加链路以减轻拥塞，监控拥塞连接并及时采取措施，可能需要调整QoS设置以保障重要业务"
        },
        "恶意活动检测":{
          "result":"识别源IP为:param_sourceip_port，目的IP为:param_targetip_port 的连接频繁进行端口扫描，可能是恶意活动",
          "sugg":"阻止恶意IP地址，端口或协议，加强网络安全措施，通知安全团队进行进一步分析，更新防火墙规则"
        },
        "流量分布分析":{
          "result":"在下午3点至5点时间段，TCP协议的流量量大幅增加，特定端口上的流量占比增加，可能与业务活动相关",
          "sugg":"根据流量分布情况进行资源规划，优化业务部署，确保网络负载均衡，可能需要在高流量时间段增加带宽"
        },
        "异常协议行为检测":{
          "result":"检测到源IP为:param_sourceip_port,目的IP为:param_targetip_port 的连接使用非标准协议，可能存在异常协议行为",
          "sugg":"对异常协议行为进行审查，可能需要禁止非标准协议，采取流量分析工具进行深入检查，确保网络安全"
        },
        "数据传输量分析":{
          "result":"源IP为:param_sourceip_port,目的IP为:param_targetip_port 的连接传输数据量超过阈值，可能存在数据泄露风险",
          "sugg":"确认数据泄露情况，加强数据加密和权限控制，阻止未经授权的数据传输，通知隐私团队进行处理"
        },
        "连接时长分析":{
          "result":"大量连接持续时间短于1秒，可能表明存在频繁的连接建立和断开，需要进一步调查",
          "sugg":"检查短连接频繁的原因，可能需要优化应用程序或配置设备以减少连接建立次数"
        },
        "服务可用性分析":{
          "result":"源IP为:param_sourceip_port,目的IP为param_targetip_port 的连接响应时间超过预设阈值，服务可用性可能受影响",
          "sugg":"优化服务响应时间，可能需要升级硬件、优化代码或增加资源，确保服务持续可用"
        },
        "数据泄露检测":{
          "result":"检测到大量未经授权的数据传输，包含敏感信息，可能存在数据泄露问题",
          "sugg":"追踪数据泄露来源，修复漏洞，强化数据保护，通知隐私团队和法务部门进行处理"
        },
        "连接速率分析":{
          "result":"param_url的传输速率从正常水平突然增加，可能表明存在异常的连接速率",
          "sugg":"确认连接速率异常的原因，可能需要调整流量控制策略，确保网络稳定性"
        },
        "网络瓶颈检测":{
          "result":"识别链路param_sourceip_port和目的IP为param_targetip_port的流量负载较高，可能是网络瓶颈",
          "sugg":"进行网络性能分析，调整链路带宽或优化流量分布，以解决瓶颈问题"
        },
        "链路负载均衡分析":{
          "result":"链路param_targetip_port的负载较高，建议进行负载均衡以优化网络性能",
          "sugg":"实施负载均衡策略，确保链路资源均衡分配，提升网络性能和可靠性"
        },
      },
      operators: [
        { label: '中国移动', value: 'ChinaMobile' },
        { label: '中国联通', value: 'ChinaUnicom' },
        { label: '中国电信', value: 'China elecom' }
        // 可以添加更多运营商选项
      ],
      provinces: [
      { label: '北京市', value: 'Beijing' },
  { label: '天津市', value: 'Tianjin' },
  { label: '河北省', value: 'Hebei' },
  { label: '山西省', value: 'Shanxi' },
  { label: '内蒙古自治区', value: 'InnerMongolia' },
  { label: '辽宁省', value: 'Liaoning' },
  { label: '吉林省', value: 'Jilin' },
  { label: '黑龙江省', value: 'Heilongjiang' },
  { label: '上海市', value: 'Shanghai' },
  { label: '江苏省', value: 'Jiangsu' },
  { label: '浙江省', value: 'Zhejiang' },
  { label: '安徽省', value: 'Anhui' },
  { label: '福建省', value: 'Fujian' },
  { label: '江西省', value: 'Jiangxi' },
  { label: '山东省', value: 'Shandong' },
  { label: '河南省', value: 'Henan' },
  { label: '湖北省', value: 'Hubei' },
  { label: '湖南省', value: 'Hunan' },
  { label: '广东省', value: 'Guangdong' },
  { label: '广西壮族自治区', value: 'Guangxi' },
  { label: '海南省', value: 'Hainan' },
  { label: '重庆市', value: 'Chongqing' },
  { label: '四川省', value: 'Sichuan' },
  { label: '贵州省', value: 'Guizhou' },
  { label: '云南省', value: 'Yunnan' },
  { label: '西藏自治区', value: 'Tibet' },
  { label: '陕西省', value: 'Shaanxi' },
  { label: '甘肃省', value: 'Gansu' },
  { label: '青海省', value: 'Qinghai' },
  { label: '宁夏回族自治区', value: 'Ningxia' },
  { label: '新疆维吾尔自治区', value: 'Xinjiang' },
  { label: '台湾省', value: 'Taiwan' },
  { label: '香港特别行政区', value: 'Hong Kong' },
  { label: '澳门特别行政区', value: 'Macao' }
      ],

      param_url_show:false,
      param_traffixlog_show:false,
      param_domain_show:false,
      param_dateRange_show:false,
      param_protocol_show:false,
      param_fxtype_show:false,
      param_sourceip_port_show:false,
      param_targetip_port_show:false,
      param_sourcedns_show:false,

      param_operator:'ChinaUnicom',
      param_province:'Beijing',
      param_url:'',
      param_domain:'www.facebook.com',
      param_dateRange:[yesterday, now], // 默认时间范围为前一天到当前时间,
      param_protocol:'http',
      param_fxtype:['异常连接检测','拥塞检测'],
      param_sourceip_port:'121.xx.xx.xx:53343',
      param_targetip_port:'192.133.77.145:80',
      param_dns:'114.114.114.114',

      dns_ip_map:{
        'www.facebook.com':'192.133.77.145',
        'www.twiter.com':'199.16.156.71',
        'www.twitter.com':'199.16.156.71'
      },
      
      currentStep:0,
      steps:[],


      running:false,
      diagnosis_result:'',
      disposal_suggestions:'',
      disposal_result:'',
      failItem:null,
      executionTimeoutList:[]
    }
  },
  methods: {
    init(formData,processor_code,processor_name) {
      if (!formData) return
      this.visible = true
      this.formData = formData
      this.exeFinishedCount = 0;
      this.exeCount = 0;
      this.exeFinished = false;
      this.param_url_show = false;
      this.param_traffixlog_show = false;
      this.param_domain_show = false;
      this.failItem = null;
      this.diagnosis_result = ''
      this.disposal_suggestions = ''
      this.disposal_result = ''
      this.step_list = []
      this.steps = []
      this.task_insert_params = {}
      if(processor_code){
        this.createSingleTask(processor_code,processor_name)
      }else{
        this.createTask(this.formData)
      }
    },
    okDisposal(){
      this.updateDiagnosisResult()

    },
    sendOrder(){
      // this.$message.success('派发处置工单')

      this.$message({
            message: '派发处置工单',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList', true)
            }
          })
    },
    cancel(){
      this.$refs.myDialog.close();
    },
    getSelectedRecords() {
      let selectedRows = this.$refs.table.selection;
      console.log('Selected Records:', selectedRows);
      return selectedRows
    },
    async executeDiag(){
      debugger
      if(this.running && !this.exeFinished){
        this.running = false
        return
      }

      this.exeFinishedCount = 0;
      this.exeCount = 0;
      this.exeFinished = false;
      this.failItem = null;
      this.diagnosis_result = ''
      this.disposal_suggestions = ''

      let sel_row = this.getSelectedRecords()
      if(!sel_row||sel_row.length==0){
        return 
      }
    
      this.running = true
      let count = this.exeNum = sel_row.length;
      for(let i=0;i<count;i++){
        let item = sel_row[i]
        item.progress = 0;
        item.diagnosis_result = '';
        item.disposal_suggestions_tip = '';
      }
      let randNum =  this.getRandomNum(0,count-1);

      /**
       * 并行
       */
      // for(let i=0;i<count;i++){
      //   let item = sel_row[i]
      //   this.simulateExecution(item,randNum==i)
      // }
      /**
       *  串行
       */
      for(let i=0;i<count;i++){
        let item = sel_row[i]
        await this.simulateExecution2(item,i,randNum==i)
      }
      
    },
    stopExecution(){
      if(!this.running){
        return
      }
      this.running = false
     
      while (this.executionTimeoutList.length > 0) {
        const item = this.executionTimeoutList.shift();
        try{
          clearTimeout(item);
        }catch(e){}
      }
    },
    handleSelectionChange(selection){
      debugger
      this.steps = []
      selection.forEach((o,i)=>{
          this.steps.push({
            'title':o.processor_name,
            'description':'等待执行',
            'status':'wait'
          })
        })   
    },
    getRandomNum (Min, Max){
          const Range = Max - Min + 1;
          const Rand = Math.random();
          return Min + Math.floor(Rand * Range);
      },
    /**
     * 模拟执行
     */
    simulateExecution(item,isfail) {
      debugger
      const interval = 100; // 时间间隔，单位毫秒
      const totalTime = this.getRandomNum(5000,10000); // 总执行时间，单位毫秒
      const steps = totalTime / interval;

      const failStep = this.getRandomNum(25,steps-10);
      
      let currentStep = 0;
      const increment = 100 / steps;
      item.progress = 0
      let executionTimeout
      const updateProgress = () => {
        if(isfail&&currentStep>=failStep){
          item.diagnosis_result='不通过'
          item.disposal_suggestions_tip = item.disposal_suggestions
          if(executionTimeout){
            clearTimeout(executionTimeout);
          }
          this.exeFinishedCount++
          if(this.exeFinishedCount>=this.exeNum){
            this.exeFinishedFun()
          }
          this.failItem = item;
          if(this.param_traffixlog_show){
            debugger
            let diagnosis_result = '"'+item.processor_name + '":不通过'
            let disposal_suggestions = item.disposal_suggestions
            let types = this.param_fxtype
            if(types&&types.length>0){
              diagnosis_result = ''
              disposal_suggestions = ''
              let randNum =  this.getRandomNum(1,3)
              let selectedNum = 0
              types.forEach((o,i)=>{
                let jObj = this.fx_results[o]
                if(jObj){
                  let randNum2 =  this.getRandomNum(0,1);
                  let r = ''+o+'的结果:'+jObj.result.replaceAll('param_sourceip_port',this.param_sourceip_port)
                                     .replaceAll('param_targetip_port',this.param_targetip_port)
                                     .replaceAll('param_url',this.param_url)
                  let r_ok = ''+o+'的结果: 正常'
                  let g = ''+o+'的处置建议:'+jObj.sugg
                  if(i==types.length-1&&selectedNum==0){
                    diagnosis_result+=r+'\n'
                    disposal_suggestions+=g+'\n'
                    selectedNum++
                  }else{
                    if(randNum2==1&&selectedNum<randNum){
                      diagnosis_result+=r+'\n'
                      disposal_suggestions+=g+'\n'
                      selectedNum++
                    }else{
                      diagnosis_result+=r_ok+'\n'
                    }
                  }
                }
              })
            }
            debugger
            this.diagnosis_result = diagnosis_result
            this.disposal_suggestions = disposal_suggestions
          }else{
            this.diagnosis_result = '"'+item.processor_name + '":不通过'
            this.disposal_suggestions = item.disposal_suggestions
          }
          return
        }
        if (currentStep < steps) {
          item.progress += increment;
          currentStep++;
          executionTimeout = setTimeout(updateProgress, interval);
          this.executionTimeoutList.push(executionTimeout)
        } else {
          item.progress = 100; // Ensure progress reaches 100
          item.diagnosis_result='通过'
          this.exeFinishedCount++
          if(this.exeFinishedCount>=this.exeNum){
              this.exeFinishedFun()
          }
        }
      };
      executionTimeout = setTimeout(updateProgress, interval);
      this.executionTimeoutList.push(executionTimeout)
    },
    simulateExecution2(item,index,isfail) {
      debugger
      return new Promise(resolve => {
        this.currentStep = index
        this.steps[index].status = 'process'
        this.steps[index].description = '执行中...'
        const interval = 100; // 时间间隔，单位毫秒
        const totalTime = this.getRandomNum(5000,10000); // 总执行时间，单位毫秒
        const steps = totalTime / interval;

        const failStep = this.getRandomNum(25,steps-10);
        
        let currentStep = 0;
        const increment = 100 / steps;
        item.progress = 0
        let executionTimeout
        const updateProgress = () => {
          if(isfail&&currentStep>=failStep){
            this.steps[index].status = 'error'
            this.steps[index].description = '不通过'
            item.diagnosis_result='不通过'
            item.disposal_suggestions_tip = item.disposal_suggestions
            if(executionTimeout){
              clearTimeout(executionTimeout);
            }
            this.exeFinishedCount++
            if(this.exeFinishedCount>=this.exeNum){
              this.exeFinishedFun()
            }
            this.failItem = item;
            if(this.param_traffixlog_show){
              debugger
              let diagnosis_result = '"'+item.processor_name + '":不通过'
              let disposal_suggestions = item.disposal_suggestions
              let types = this.param_fxtype
              if(types&&types.length>0){
                diagnosis_result = ''
                disposal_suggestions = ''
                let randNum =  this.getRandomNum(1,3)
                let selectedNum = 0
                types.forEach((o,i)=>{
                  let jObj = this.fx_results[o]
                  if(jObj){
                    let randNum2 =  this.getRandomNum(0,1);
                    let r = ''+o+'的结果:'+jObj.result.replaceAll('param_sourceip_port',this.param_sourceip_port)
                                      .replaceAll('param_targetip_port',this.param_targetip_port)
                                      .replaceAll('param_url',this.param_url)
                    let r_ok = ''+o+'的结果: 正常'
                    let g = ''+o+'的处置建议:'+jObj.sugg
                    if(i==types.length-1&&selectedNum==0){
                      diagnosis_result+=r+'\n'
                      disposal_suggestions+=g+'\n'
                      selectedNum++
                    }else{
                      if(randNum2==1&&selectedNum<randNum){
                        diagnosis_result+=r+'\n'
                        disposal_suggestions+=g+'\n'
                        selectedNum++
                      }else{
                        diagnosis_result+=r_ok+'\n'
                      }
                    }
                  }
                })
              }
              debugger
              this.diagnosis_result = diagnosis_result
              this.disposal_suggestions = disposal_suggestions
            }else{
              this.diagnosis_result = '"'+item.processor_name + '":不通过'
              this.disposal_suggestions = item.disposal_suggestions
            }
            resolve();
            return
          }
          if (currentStep < steps) {
            item.progress += increment;
            currentStep++;
            executionTimeout = setTimeout(updateProgress, interval);
            this.executionTimeoutList.push(executionTimeout)
          } else {
            item.progress = 100; // Ensure progress reaches 100
            item.diagnosis_result='通过'
            this.steps[index].status = 'finish'
            this.steps[index].description = '执行完成：通过'
            this.exeFinishedCount++
            if(this.exeFinishedCount>=this.exeNum){
                this.exeFinishedFun()
            }
            resolve();
          }
        };
        executionTimeout = setTimeout(updateProgress, interval);
        this.executionTimeoutList.push(executionTimeout)
      });
    },
    formatProgress(progress) {
      return parseInt((progress).toFixed(0));
    },
    exeFinishedFun(){
      this.exeFinished = true
      this.updateDiagnosisStatus()
    },
    getProgressStatus(progress) {
      if (progress >= 99) {
        return 'success';
      } else {
        return '';
      }
    },
    updateDiagnosisStatus(){
      let url = '/api/system/DataInterface/457600254498309189/Actions/Call'
      let params = {
          "tenant_id": "",
          "paramList": [
              {
                  "field": "id", "value": this.formData.f_id
              },
              {
                  "field": "diagnosis_status", "value": "已诊断"
              },
              {
                  "field": "diagnosis_result", "value": this.failItem?('"'+this.failItem.processor_name + '":不通过'):"未检查到问题"
              },
              {
                  "field": "disposal_suggestions", "value": this.failItem?(this.failItem.disposal_suggestions):""
              }
          ]
      }
      request(
        {
          url: url,
          method: 'post',
          data:params
        }).then(res => {

        }).catch(res=>{

        })

    },
    updateDiagnosisResult(){
      /**
       * 更新故障工单的处置结果
       */
      let url = '/api/system/DataInterface/457603278822179909/Actions/Call'
      let params = {
          "tenant_id": "",
          "paramList": [
              {
                  "field": "id", "value": this.formData.f_id
              },
              {
                  "field": "diagnosis_status", "value": "已诊断"
              },
              {
                  "field": "dispose_status", "value": "已处置"
              },
              {
                  "field": "diagnosis_result", "value": this.failItem?('"'+this.failItem.processor_name + '":不通过'):"未检查到问题"
              },
              {
                  "field": "disposal_suggestions", "value": this.failItem?(this.failItem.disposal_suggestions):""
              },
              {
                  "field": "disposal_result", "value": this.disposal_result
              }
          ]
      }
      request(
        {
          url: url,
          method: 'post',
          data:params
        }).then(res => {
          this.$message({
            message: '故障处置完成，本次处置将存入故障知识库中，为后续机器学习自动化故障诊断提供数据',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList', true)
            }
          })
        }).catch(res=>{

        })

    },
    createSingleTask(processor_code,processor_name){
      debugger
      if(processor_name == '外部拨测国际网站'
        || processor_name.indexOf('网站无法访问')>-1){
        this.param_url_show = true
      } else if(processor_name.indexOf('访问日志分析')>-1){
        this.faultinfo.fault_desc = '基于流量日志进行异常分析'
        // this.param_url_show = true
        this.param_traffixlog_show = true
      } else{
        if(processor_name.indexOf('流量日志')>-1){
          this.param_domain_show = true
        }
      }
      let sel_taskstepinfo_url = '/api/system/DataInterface/455266965334786053/Actions/Call'
      debugger
      let params = {
            "tenant_id": "",
            "paramList": [
                {
                    // "field": "processor_codes", "value": '"'+processor_code+'"'
                    "field": "processor_codes", "value": processor_code
                }
            ]
        }
      request(
          {
            url: sel_taskstepinfo_url,
            method: 'post',
            data:params
          }
        ).then(res2 => {
            debugger
            let items = res2.code == 200 && res2.data && res2.data.data && res2.data.data.length > 0 ? res2.data.data : []
            if (items.length > 0) {
                debugger
                 // console.log(value,index)
                for (let i = 0; i < items.length; i++) {
                  let item2 = items[i]
                  item2.step = this.step_list.length+1
                  item2.progress=0
                  item2.diagnosis_result=''
                  item2.disposal_suggestions_tip = ''
                  this.step_list.push(item2)
                }
                this.$nextTick(()=>{
                  debugger
                  this.step_list.forEach(item => {
                    if(items.length==1||item.isoften=='是'){
                      item.selected = true;
                      this.$refs.table.toggleRowSelection(item, true) //指定元素取消选中：ele要取消选中的元素,fasle取消选中,true为选中
                    }
                  });
                })
            }else{
              /**
               * 没有查询到故障诊断编排步骤
               */
            }

        }).catch(res2 => {
            this.$message.error('创建诊断任务步骤信息失败:' + res2)
            // console.log(res)
            debugger
        })
    },
    createTask(data){
      debugger
      let sel_taskinfo_url = '/api/system/DataInterface/455255245669269509/Actions/Call'
      let sel_taskstepinfo_url = '/api/system/DataInterface/455266965334786053/Actions/Call'
      let insert_task_url = '/api/system/DataInterface/455219848255897605/Actions/Call'
      let insert_task_step_url = '/api/system/DataInterface/455245488073998341/Actions/Call'
      debugger
      let fault_record_id = data.f_id
      let fault_code = data.fault_code
      let fault_name = data.fault_name
     
      let params = {
          "tenant_id": "",
          "paramList": [
              {
                  "field": "fault_record_id", "value": fault_record_id
              },
              {
                  "field": "fault_code", "value": fault_code
              }
          ]
      }
      
      request(
        {
          url: sel_taskinfo_url,
          method: 'post',
          data:params
        }).then(res => {
          // console.log(res)
          let item = res.code == 200 && res.data && res.data.data && res.data.data.length > 0 ? res.data.data[0] : null
          if (item) {
              this.faultinfo = item
              let { fault_params, fault_name, node_code, pipeline_id, node_name,fault_desc, processors } = item
              let json_processors = JSON.parse(processors)
              let step_count = json_processors.length
              if(fault_name.indexOf('网站不可访问')>-1){
                let o_fault_params = JSON.parse(fault_params)
                this.param_sourceip_port = o_fault_params.ip+':59152'
                this.param_dns = o_fault_params.dns
                this.param_domain = o_fault_params.url.replaceAll('https://','').replaceAll('http://','')
                this.param_targetip_port = this.dns_ip_map[this.param_domain]?this.dns_ip_map[this.param_domain]+':80':''
                this.param_domain_show = true
              }
              debugger
              params = {
                  "tenant_id": "",
                  "paramList": [
                      {
                          "field": "processor_codes", "value": processors.replace('[', '').replace(']', '')
                      }
                  ]
              }

              request(
                {
                  url: sel_taskstepinfo_url,
                  method: 'post',
                  data:params
                }
              ).then(res2 => {
                  debugger
                  let items = res2.code == 200 && res2.data && res2.data.data && res2.data.data.length > 0 ? res2.data.data : []
                  if (items.length > 0) {
                      let task_id = this.hlsz.guid()
                      this.task_insert_params = {
                          "tenant_id": "",
                          "paramList": [
                              {
                                  "field": "id", "value": task_id
                              },
                              {
                                  "field": "fault_record_id", "value": fault_record_id
                              }
                              , {
                                  "field": "pipeline_id", "value": pipeline_id
                              }
                              ,
                              {
                                  "field": "node_code", "value": node_code
                              }, {

                                  "field": "node_name", "value": node_name
                              }, {
                                  "field": "fault_code", "value": fault_code
                              }, {
                                  "field": "fault_name", "value": fault_name
                              }
                              , {
                                  "field": "params", "value": fault_params
                              }
                              , {
                                  "field": "status", "value": "running"
                              }
                              , {
                                  "field": "step_count", "value": step_count
                              }, {
                                  "field": "step_current", "value": 1
                              }
                          ]
                      }
                      debugger
                      json_processors.forEach((value,index)=>{
                          // console.log(value,index)
                          for (let i = 0; i < items.length; i++) {
                            let item2 = items[i]
                            let { processor_code } = item2
                            if(processor_code==value){
                              item2.step = this.step_list.length+1
                              item2.progress=0
                              item2.diagnosis_result=''
                              item2.disposal_suggestions_tip = ''
                              this.step_list.push(item2)
                            }
                          }
                      })

                      this.$nextTick(()=>{
                        debugger
                        this.step_list.forEach(item => {
                          if(item.isoften=='是'){
                            item.selected = true;
                            this.$refs.table.toggleRowSelection(item, true) //指定元素取消选中：ele要取消选中的元素,fasle取消选中,true为选中
                          }
                
                        });
                      })
                  }else{
                    /**
                     * 没有查询到故障诊断编排步骤
                     */
                  }

              }).catch(res2 => {
                  this.$message.error('创建诊断任务步骤信息失败:' + res2)
                  // console.log(res)
                  debugger
              })

          }else{
            /**
             * 没有查询到故障诊断编排
             */

          }
      }).catch(res => {
          // console.log(res)
          this.$message.error('创建诊断任务信息失败:'+res)
          debugger
      })
    },
   
    handleSuccess(res, file) {
      this.btnLoading = false
      debugger
      if (res.code == 200) {
        if(res.data&&res.data.url){
          this.$message({
            message: '导入完成，正在下载错误数据...',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList', true)
            }
          })
          this.jnpf.downloadFile(res.data.url)
        }else{
          this.$message({
            message: '导入成功',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList', true)
            }
          })
        }  
      } else {
        this.$message({ message: '导入失败', type: 'error', duration: 1000 })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 40px 30px !important;
  max-height: 100vh  !important;
}
.no-wrap-cell {
  white-space: nowrap;
}
/* 可以根据需要添加自定义样式 */
.progress-container {
  position: relative;
  display: flex;
  align-items: center;
}

.progress-bar {
  flex: 1;
}

.status-icon {
  display: flex;
  align-items: center;
  font-size: 20px;
}

.success-icon {
  margin-left: 10px;
  color: #67c23a;
}
.exception-icon {
  margin-right: 10px;
  color: #f56c6c;
}

.input-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-label {
  margin-right: 10px;
}
.grid-content {
  &:first-child {
    border-right: 1px solid #dcdfe6;
  }

  text-align: center;

  p {
    text-align: center;
  }

  img {
    width: 128px;
    margin: 10px 0;
  }

  .truncate-lines {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 12; /* 设置最大显示行数 */
  line-height: 1.5; /* 行高，可根据实际情况调整 */
}
  .radio-row {
    display: flex; /* 使用 Flex 布局 */
    align-items: center; /* 垂直居中 */
  }
  .custom-form-item .el-form-item__label {
    width: 150px; /* 设置相同的宽度 */
    text-align: left;
  }
::v-deep .el-step__title {
  font-size: 12px !important;
  line-height:16px !important;
}
::v-deep .el-step__title.is-process {
  color: blue !important; /* 设置进行中步骤的字体颜色 */
}

::v-deep .el-step__title.is-wait {
  color: rgb(24, 24, 23) !important; /* 设置等待中步骤的字体颜色 */
}

::v-deep .el-step__title.is-finish {
  color: green !important; /* 设置已完成步骤的字体颜色 */
}
::v-deep .el-step__title.is-error {
  color: red !important; /* 设置已完成步骤的字体颜色 */
}

::v-deep .el-step__description.is-process {
  color: blue !important; /* 设置进行中步骤的字体颜色 */
}

::v-deep .el-step__description.is-wait {
  color: rgb(24, 24, 23) !important; /* 设置等待中步骤的字体颜色 */
}

::v-deep .el-step__description.is-finish {
  color: green !important; /* 设置已完成步骤的字体颜色 */
}
::v-deep .el-step__description.is-error {
  color: red !important; /* 设置已完成步骤的字体颜色 */
}
}
</style>